﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Threading;
using System.ComponentModel;
using System.Net;
using System.Net.NetworkInformation;

namespace KD.DAS.Component.Data
{
    public class DataHelper
    {


        private static bool _bOpen = false;
        private static Thread _thrdNet;
        private static bool _bRun = false;

        /// <summary>
        /// 参数初始化状态
        /// </summary>
        [Description("参数初始化状态")]
        public static bool IsOpen
        {
            get
            {
                return _bOpen;
            }
        }

        /// <summary>
        /// 初始化连接参数
        /// </summary>
        /// <returns></returns>
        [Description("初始化连接参数")]
        public static bool DoInit()
        {
            try
            {
                Configer.IP = System.Configuration.ConfigurationManager.AppSettings["IP"];
                Configer.Port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["Port"].ToString());
                Configer.TimeOut = int.Parse(System.Configuration.ConfigurationManager.AppSettings["TimeOut"].ToString());
                Configer.QuerySql = System.Configuration.ConfigurationManager.AppSettings["QuerySql"];
                Configer.ExecSql = System.Configuration.ConfigurationManager.AppSettings["ExecSql"];
                Configer.ExecProc = System.Configuration.ConfigurationManager.AppSettings["ExecProc"];
                Configer.IsDebug = System.Configuration.ConfigurationManager.AppSettings["IsDebug"].ToString() == "1";
                Configer.Url = "http://" + Configer.IP + ":" + Configer.Port.ToString();

                if (Configer.TimeOut > 0
                    && Configer.Port > 0
                    && !string.IsNullOrEmpty(Configer.IP)
                    && !string.IsNullOrEmpty(Configer.Url)
                    && !string.IsNullOrEmpty(Configer.QuerySql)
                    && !string.IsNullOrEmpty(Configer.ExecSql)
                    && !string.IsNullOrEmpty(Configer.ExecProc))
                {
                    //启动服务端网络监听
                    _thrdNet = new Thread(new ThreadStart(DoListenNet));
                    _thrdNet.IsBackground = true;
                    _bRun = true;
                    _thrdNet.Start();
                    _bOpen = true;
                }
                else
                {
                    _bOpen = false;
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, "DataOperator.DoInit()参数有误..");
                }
                if (Configer.IsDebug)
                {
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, string.Format("IP:{0}\t", Configer.IP));
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, string.Format("Port:{0}\t", Configer.Port));
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, string.Format("Url:{0}\t", Configer.Url));
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, string.Format("TimeOut:{0}\t", Configer.TimeOut));
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, string.Format("QuerySql:{0}\t", Configer.QuerySql));
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, string.Format("ExecSql:{0}\t", Configer.ExecSql));
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, string.Format("ExecProc:{0}\t", Configer.ExecProc));
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, string.Format("IsDebug:{0}\t", Configer.IsDebug));
                }
            }
            catch (Exception ex)
            {
                _bOpen = false;
                KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, "DataOperator.DoInit()出错了..");
                KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, ex.ToString());
                KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, ex.StackTrace);
            }
            return IsOpen;
        }


        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <returns></returns>
        [Description("关闭连接")]
        public static void DoDispose()
        {
            _bRun = false;
            if (_thrdNet != null)
                _thrdNet.Abort();
        }

        /// <summary>
        /// 查询Sql语句获取结果集
        /// </summary>
        /// <param name="_User">登陆用户对象</param>
        /// <param name="_strSql">查询语句</param>
        /// <returns></returns>
        public static KD.DAS.Component.Data.EntityQuerySql QuerySql(string _strUser, string _strPwd, string _strSql)
        {
            Titan.Core.DasClientResult result;
            KD.DAS.Component.Data.EntityQuerySql _modelQuerySql;
            if (IsOpen)
            {
                try
                {
                    //序列化业务请求实体对象到Json字符串
                    var _dasMsg = new Titan.DAS.Msg.Common.DasMsgQuerySql(_strSql);
                    var _reqContentPlain = JsonConvert.SerializeObject(_dasMsg);
                    //发送POST请求获得响应数据
                    result = Titan.Core.DasClinet.SendPost(Configer.Url + Configer.QuerySql, Configer.TimeOut, true, _strUser, _strPwd, _reqContentPlain);
                    if (!result.IsSuccess || result.StatusCode != 1)
                    {
                        if (!Configer.IsConnect)
                            _modelQuerySql = new EntityQuerySql(false, -3, "网络连接中断", null);
                        else
                            _modelQuerySql = new EntityQuerySql(false, result.StatusCode, result.StatusDesc, null);
                    }
                    else
                    {
                        //反序列响应数据到具体的业务响应实体对象
                        JsonSerializerSettings jsonSet = new JsonSerializerSettings();
                        jsonSet.NullValueHandling = NullValueHandling.Ignore;
                        _dasMsg = JsonConvert.DeserializeObject<Titan.DAS.Msg.Common.DasMsgQuerySql>(result.ResponseContentPlain, jsonSet);
                        if (result.StatusCode != 1)
                            _modelQuerySql = new EntityQuerySql(false, result.StatusCode, result.StatusDesc, _dasMsg.ResultDataset);
                        else
                            _modelQuerySql = new EntityQuerySql(true, result.StatusCode, result.StatusDesc, _dasMsg.ResultDataset);
                    }
                }
                catch (Exception ex)
                {
                    _modelQuerySql = new EntityQuerySql(false, -1, ex.ToString(), null);
                }
            }
            else
            {
                _modelQuerySql = new EntityQuerySql(false, -2, "数据操作链接未打开", null);
            }
            return _modelQuerySql;
        }



        /// <summary>
        /// 查询Sql语句获取结果集
        /// </summary>
        /// <param name="_User">登陆用户对象</param>
        /// <param name="_strSql">查询语句</param>
        /// <returns></returns>
        public static KD.DAS.Component.Data.EntityExecSql ExecSql(string _strUser, string _strPwd, string _strSql)
        {
            Titan.Core.DasClientResult result;
            KD.DAS.Component.Data.EntityExecSql _modelExecSql;
            if (IsOpen)
            {
                try
                {
                    //序列化业务请求实体对象到Json字符串
                    var _dasMsg = new Titan.DAS.Msg.Common.DasMsgExecSql(_strSql, 0);
                    var _reqContentPlain = JsonConvert.SerializeObject(_dasMsg);
                    //发送POST请求获得响应数据
                    result = Titan.Core.DasClinet.SendPost(Configer.Url + Configer.ExecSql, Configer.TimeOut, true, _strUser, _strPwd, _reqContentPlain);
                    if (!result.IsSuccess || result.StatusCode != 1)
                    {
                        if (!Configer.IsConnect)
                            _modelExecSql = new EntityExecSql(false, -3, "网络连接中断", 0);
                        else
                            _modelExecSql = new EntityExecSql(false, result.StatusCode, result.StatusDesc, 0);
                    }
                    else
                    {
                        //反序列响应数据到具体的业务响应实体对象
                        JsonSerializerSettings jsonSet = new JsonSerializerSettings();
                        jsonSet.NullValueHandling = NullValueHandling.Ignore;
                        _dasMsg = JsonConvert.DeserializeObject<Titan.DAS.Msg.Common.DasMsgExecSql>(result.ResponseContentPlain, jsonSet);
                        if (result.StatusCode != 1)
                            _modelExecSql = new EntityExecSql(false, result.StatusCode, result.StatusDesc, _dasMsg.AffectedRowNum);
                        else
                            _modelExecSql = new EntityExecSql(true, result.StatusCode, result.StatusDesc, _dasMsg.AffectedRowNum);
                    }
                }
                catch (Exception ex)
                {
                    _modelExecSql = new EntityExecSql(false, -1, ex.ToString(), 0);
                }
            }
            else
            {
                _modelExecSql = new EntityExecSql(false, -2, "数据操作链接未打开", 0);
            }
            return _modelExecSql;
        }


        /// <summary>
        /// 查询Sql语句获取结果集
        /// </summary>
        /// <param name="_User">登陆用户对象</param>
        /// <param name="_strSql">查询语句</param>
        /// <returns></returns>
        public static KD.DAS.Component.Data.EntityExecProc ExecProc(string _strUser, string _strPwd, string _strSql, Titan.DAS.Msg.Common.ProcParam[] _Parms)
        {
            Titan.Core.DasClientResult result;
            KD.DAS.Component.Data.EntityExecProc _modelExecSql;
            if (IsOpen)
            {
                try
                {
                    //序列化业务请求实体对象到Json字符串
                    var _dasMsg = new Titan.DAS.Msg.Common.DasMsgExecProc(_strSql, _Parms);
                    var _reqContentPlain = JsonConvert.SerializeObject(_dasMsg);
                    //发送POST请求获得响应数据
                    result = Titan.Core.DasClinet.SendPost(Configer.Url + Configer.ExecProc, Configer.TimeOut, true, _strUser, _strPwd, _reqContentPlain);
                    if (!result.IsSuccess || result.StatusCode != 1)
                    {
                        if (!Configer.IsConnect)
                            _modelExecSql = new EntityExecProc(false, -3, "网络中断", null, null);
                        else
                            _modelExecSql = new EntityExecProc(false, result.StatusCode, result.StatusDesc, null, null);
                    }
                    else
                    {
                        //反序列响应数据到具体的业务响应实体对象
                        JsonSerializerSettings jsonSet = new JsonSerializerSettings();
                        jsonSet.NullValueHandling = NullValueHandling.Ignore;
                        _dasMsg = JsonConvert.DeserializeObject<Titan.DAS.Msg.Common.DasMsgExecProc>(result.ResponseContentPlain, jsonSet);
                        _modelExecSql = new EntityExecProc(true, result.StatusCode, result.StatusDesc, _dasMsg.ResultDataset, _dasMsg.ProcParams);
                    }
                }
                catch (Exception ex)
                {
                    _modelExecSql = new EntityExecProc(false, -1, ex.ToString(), null, null);
                }
            }
            else
            {
                _modelExecSql = new EntityExecProc(false, -2, "数据操作链接未打开", null, null);
            }
            return _modelExecSql;
        }

        /// <summary>
        /// 监听网络
        /// </summary>
        private static void DoListenNet()
        {
            while (_bRun)
            {
                DoPingIPStatus();
                System.Threading.Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// 检测网络状态
        /// </summary>
        private static void DoPingIPStatus()
        {
            try
            {
                Ping ping = new Ping();
                PingOptions pingOptions = new PingOptions();
                pingOptions.DontFragment = true;
                string s = "test";
                byte[] bytes = Encoding.ASCII.GetBytes(s);
                int timeout = 120;
                PingReply pingReply = ping.Send(Configer.IP, timeout, bytes, pingOptions);
                if (pingReply.Status == IPStatus.Success)
                {
                    Configer.IsConnect = true;
                    Configer.Url = "http://" + Configer.IP + ":" + Configer.Port.ToString();
                }
                else
                {
                    KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, string.Format("服务器[{0}]网络不通", Configer.IP));
                }
            }
            catch (Exception ex)
            {
                KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, "DataOperator.DoPingIPStatus()网络状态监听出错了...");
                KD.Log.LogHelper.DoWriteLogTypeSubitem(KD.Log.LogType.Information, Log.LogSubitem.DAS, ex.ToString());
            }
        }


    }
}
